import 'dart:async';
import 'dart:typed_data';

import 'package:chop/Model/POLI_entity.dart';
import 'package:chop/Model/order_entity.dart';
import 'package:chop/common/DioUtils.dart';
import 'package:chop/common/StringUtils.dart';
import 'package:chop/common/configs.dart';
import 'package:chop/view/pay/pay_list.dart';
import 'package:chop/view/pay/poli_pay.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:chop/widgets/appBar.dart';
import 'package:chop/widgets/behavior.dart';
import 'package:chop/widgets/loadingDialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:google_map_polyline/google_map_polyline.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:loading_animations/loading_animations.dart';
import 'dart:ui' as ui;
import 'package:chop/view/home/place_an_order/Delivery_order.dart';

//正在进行订单
class OrderUnpaid extends StatefulWidget {
  final String uuid;

  const OrderUnpaid({Key key, this.uuid}) : super(key: key);

  @override
  _OrdedrUnfinishedState createState() => _OrdedrUnfinishedState();
}

class _OrdedrUnfinishedState extends State<OrderUnpaid> {
  // 是否在网络请求中
  bool isNetworkNotBad = false;

  String uuid;

  orderData data;
  GoogleMapPolyline googleMapPolyline =
      GoogleMapPolyline(apiKey: Configs.API_KEY);
  Set<Marker> Markers = Set();

  // 地图控制器
  Completer<GoogleMapController> _controller = Completer();

  Widget getBody() {
    if (isNetworkNotBad) {
      print("加载完成");
      return _buildBody();
//      return ListView.builder(
//        itemBuilder: (context, index) {
//          return _buildBody();
//        },
//        itemCount: 5,
//      );
    } else {
      print("正在加载");
      return Center(child: LoadingJumpingLine.square());
    }
  }

  Widget _buildBody() {
    return Container(
//      width: MediaQuery.of(context).size.width,
//      height: MediaQuery.of(context).size.height,
      child: Stack(
        children: <Widget>[
          GoogleMap(
            initialCameraPosition: CameraPosition(
              target: LatLng(
                  double.parse(data.beginLat), double.parse(data.beginLng)),
              zoom: 14.4746,
            ),
            polylines: Set<Polyline>.of(_polylines.values),
            markers: Markers,
            onMapCreated: (GoogleMapController controller) {
              _controller.complete(controller);
            },
          ),
          Positioned(
              bottom: 10,
              height: 300,
              width: MediaQuery.of(context).size.width,
              child: ScrollConfiguration(
                behavior: MyBehavior(),
                child: ListView(
                  children: <Widget>[
                    Container(
                      height: 10,
                    ),
                    getColumn("订单信息",
                        child: Column(
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Column(
                                      children: <Widget>[
                                        Row(
                                          children: <Widget>[
                                            Container(
//                        width: double.infinity,
                                              padding: EdgeInsets.only(
                                                  top: 5, bottom: 5),
                                              child: FixedSizeText(
                                                "订单号：${data.uuid}",
                                                textAlign: TextAlign.start,
                                                style: TextStyle(
                                                    fontSize: 16,
                                                    fontWeight:
                                                        FontWeight.bold),
                                              ),
                                            )
                                          ],
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Container(
//                        width: double.infinity,
                                              padding: EdgeInsets.only(
                                                  top: 5, bottom: 5),
                                              child: FixedSizeText(
                                                "订单状态：${getStatus(data.status)}",
                                                textAlign: TextAlign.start,
                                                style: TextStyle(
                                                  fontSize: 16,
                                                ),
                                              ),
                                            )
                                          ],
                                        ),
                                        Container(
                                          padding: EdgeInsets.only(
                                              top: 5, bottom: 5),
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.subdirectory_arrow_right,
                                                size: 15,
                                                color: Colors.greenAccent,
                                              ),
                                              Container(
                                                width: 5,
                                              ),
                                              Expanded(
                                                child: FixedSizeText(
                                                  "${data.begin}",
                                                  textAlign: TextAlign.left,
                                                  maxLines: 4,
//                        overflow: TextOverflow.ellipsis,
                                                  style: TextStyle(),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.only(
                                              top: 5, bottom: 5),
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.subdirectory_arrow_left,
                                                size: 15,
                                                color: Colors.redAccent,
                                              ),
                                              Container(
                                                width: 5,
                                              ),
                                              Expanded(
                                                child: FixedSizeText(
                                                  "${data.end}",
                                                  textAlign: TextAlign.left,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: TextStyle(),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                    flex: 8,
                                  ),
                                ],
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.only(top: 10, bottom: 10),
                              margin: EdgeInsets.only(left: 50, right: 50),
                              child: RaisedButton(
                                //提交按钮
                                color: Colors.lightBlueAccent,
                                highlightColor: Colors.blueAccent,
                                splashColor: Colors.blue,
                                colorBrightness: Brightness.dark,
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(10)),
                                onPressed: () async {
                                  if (StringUtils.isNotNull(data.pay) &&
                                      StringUtils.isNotNull(
                                          data.transactionRefNo)) {
                                    print(
                                        "支付方式为：${data.pay} , 订单号： ${data.transactionRefNo}");
                                    if (data.pay == "0") {
                                      // POLI
                                      showDialog<Null>(
                                        context: context, //BuildContext对象
                                        barrierDismissible: false,
                                        builder: (BuildContext context) {
                                          return LoadingDialog(
                                            //调用对话框
                                            text: 'Loading...',
                                          );
                                        },
                                      );
                                      await DioUtils.sendPOLI(data)
                                          .then((POLIEntity poliEntity) {
                                        if (poliEntity.success) {
                                          Get.back();
                                          Get.to(PoliPay(
                                            url: poliEntity.navigateURL,
                                          ));
                                        }
                                      });
                                    }
                                  } else {
                                    Get.to(PayList(
                                      orderdata: data,
                                    ));
                                  }
                                },
                                child: FixedSizeText(
                                  '立即支付',
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 15),
                                ),
                              ),
                            ),
                          ],
                        )),
                    getColumn(
                      "路程",
                      child: Column(
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Container(
                                  child: FixedSizeText(
                                    "路程",
                                    style: TextStyle(color: Colors.black45),
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  alignment: Alignment.topRight,
                                  child: FixedSizeText("${data.distance} km   "),
                                ),
                              )
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Expanded(
                                child: Container(
                                  child: FixedSizeText(
                                    "跑腿费",
                                    style: TextStyle(color: Colors.black45),
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  alignment: Alignment.topRight,
                                  child: FixedSizeText("${data.money} \$   "),
                                ),
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                      getColumn("备注",
                        child: Container(
                          child: FixedSizeText(data.remark ?? ""),
                        ))
                  ],
                ),
              )),
        ],
      ),
    );
  }

  String getStatus(String status) {
    switch (status) {
      case "0":
        return "进行中";
      case "1":
        return "已完成";
      case "2":
        return "未付款";
      case "3":
        return "待接单";
    }
  }

  Widget _getButton(
    String title, {
    Icon icon,
    VoidCallback click,
  }) {
    return Expanded(
      flex: 2,
      child: GestureDetector(
        child: Center(heightFactor: 2, child: FixedSizeText(title)),
        onTap: click,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BaseViewBar(
        childView: BaseTitleBar("订单详情"),
        preferredSize: Size.fromHeight(50.0),
      ),
      body: getBody(),
    );
  }

  @override
  void initState() {
    this.uuid = widget.uuid;
    // TODO: implement initState
    super.initState();
    getData();
  }

  Future<void> getData() async {
    await DioUtils.orderInfo(uuid).then((Map result) async {
      if (result['code'] == 0) {
        data = orderData.fromJson(result['data']);
        // 请求路线坐标
        List<LatLng> _coordinates =
            await googleMapPolyline.getCoordinatesWithLocation(
                origin: LatLng(
                    double.parse(data.beginLat), double.parse(data.beginLng)),
                destination: LatLng(
                    double.parse(data.endLat), double.parse(data.endLng)),
                mode: RouteMode.driving);
        //图标
//        final Uint8List markerIcon =
//            await getBytesFromAsset('asset/map/begin.png', 150);
//        final Uint8List endIcon =
//            await getBytesFromAsset('asset/map/end.png', 150);
        // 标记起送地点
        Markers.add(Marker(
            markerId: MarkerId("begin"),
            infoWindow: InfoWindow(
              title: "起送地点",
            ),
//            icon: BitmapDescriptor.fromBytes(markerIcon),
            position: LatLng(
                double.parse(data.beginLat), double.parse(data.beginLng))));
        // 标记送达地点
        Markers.add(Marker(
            markerId: MarkerId("end"),
            infoWindow: InfoWindow(
              title: "送达地点",
            ),
//            icon: BitmapDescriptor.fromBytes(endIcon),
            position:
                LatLng(double.parse(data.endLat), double.parse(data.endLng))));
        _addPolyline(_coordinates);
        setState(() {
          isNetworkNotBad = true;
        });
      }
    });
  }

  int _polylineCount = 1;
  List<List<PatternItem>> patterns = <List<PatternItem>>[
    <PatternItem>[], //line
    <PatternItem>[PatternItem.dash(30.0), PatternItem.gap(20.0)], //dash
    <PatternItem>[PatternItem.dot, PatternItem.gap(10.0)], //dot
    <PatternItem>[
      //dash-dot
      PatternItem.dash(30.0),
      PatternItem.gap(20.0),
      PatternItem.dot,
      PatternItem.gap(20.0)
    ],
  ];
  Map<PolylineId, Polyline> _polylines = <PolylineId, Polyline>{};

  _addPolyline(List<LatLng> _coordinates) {
    PolylineId id = PolylineId("poly$_polylineCount");
    Polyline polyline = Polyline(
        polylineId: id,
        patterns: patterns[0],
        color: Colors.blueAccent,
        points: _coordinates,
        width: 10,
        onTap: () {});

    setState(() {
      _polylines[id] = polyline;
      _polylineCount++;
    });
  }

// 获取图标 base64
  Future<Uint8List> getBytesFromAsset(String path, int width) async {
    ByteData data = await rootBundle.load(path);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width);
    ui.FrameInfo fi = await codec.getNextFrame();
    return (await fi.image.toByteData(format: ui.ImageByteFormat.png))
        .buffer
        .asUint8List();
  }
}
